import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api"
import { setToken, getToken, removeToken } from "@/utils/token";
//登录与注册的仓库
const state = {
    code: "",
    token: getToken(),
    userInfo: {}
}
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //清除本地数据
    CLEAR(state) {
        //帮仓库关掉、清空用户信息
        state.token = '';
        state.userInfo = {};
        //本地存储清空
        removeToken();
    }
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result9 = await reqGetCode(phone)
        if (result9.code == 200) {
            commit('GETCODE', result9.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result10 = await reqUserRegister(user);
        console.log(result10)
        if (result10.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //登录页面【token】
    async userLogin({ commit }, data) {
        let result11 = await reqUserLogin(data);
        if (result11.code == 200) {
            commit("USERLOGIN", result11.data.token);
            //持久化存储token
            setToken(result11.data.token);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    //token获取用户信息（需要存储用户的信息，所以需要三连环）
    async getUserInfo({ commit }) {
        let result12 = await reqUserInfo();
        if (result12.code == 200) {
            //提交用户信息
            commit("GETUSERINFO", result12.data);
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"));
        }
    },
    //退出登录
    async userLogout({ commit }) {
        //知识向服务器发起一次请求，通知服务器清除token
        let result13 = await reqLogout();
        //actions将数据提交到mutations里修改state
        if (result13.code == 200) {
            commit("CLEAR");
            return 'ok';
        } else {
            return Promise.reject(new Error("faile"))
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}